<script setup>
import { ref } from 'vue'
import api from '@/utils/api'
import Toast from '@/components/Toast.vue'
import { showToast } from '@/utils/toast'

// 用户信息
const currentUsername = ref('') // 当前用户名
const currentPhone = ref('') // 当前手机号
const currentPassword = ref('********') // 默认显示星号

// 表单数据
const newPassword = ref('') // 新密码
const confirmPassword = ref('') // 确认密码
const newPhone = ref('') // 新手机号
const newUsername = ref('') // 新用户名
const verifyCode = ref('') // 验证码

// 显示状态
const showPasswordForm = ref(false) // 控制密码表单显示
const showPhoneForm = ref(false) // 控制手机号表单显示
const showUsernameForm = ref(false) // 控制用户名表单显示

// 验证码倒计时
const countdown = ref(0) // 倒计时秒数
const timer = ref(null) // 定时器引用

// 获取当前用户信息
const getCurrentUserInfo = async () => {
  try {
    const response = await api.get('/api/get_user_info')
    if (response.data.code === 0) {
      currentUsername.value = response.data.data.username.username
      currentPhone.value = response.data.data.phone
    }
  } catch (error) {
    showToast('获取用户信息失败', 'error')
  }
}

// 页面加载时获取用户信息
getCurrentUserInfo()

// 更新用户名相关
const handleUpdateUsername = async () => {
  if (!newUsername.value.trim()) {
    showToast('用户名不能为空', 'error')
    return
  }
  if (newUsername.value.length < 4 || newUsername.value.length > 16) {
    showToast('用户名长度必须在4-16个字符之间', 'error')
    return
  }
  
  try {
    const response = await api.post('/api/update_username', {
      new_username: newUsername.value
    })
    
    if (response.data.code === 0) {
      showToast('用户名更新成功，请重新登录', 'success')
      currentUsername.value = newUsername.value
      localStorage.removeItem('token')
      setTimeout(() => {
        window.location.href = '/'
      }, 1500)
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('请求失败，请稍后重试', 'error')
  }
}

// 密码相关
const validatePasswordForm = () => {
  if (!newPassword.value.trim()) {
    showToast('请输入新密码', 'error')
    return false
  }
  if (!confirmPassword.value.trim()) {
    showToast('请确认新密码', 'error')
    return false
  }
  if (!/^[a-zA-Z0-9]{6,16}$/.test(newPassword.value)) {
    showToast('新密码必须是6-16位字母或数字的组合', 'error')
    return false
  }
  if (newPassword.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致', 'error')
    return false
  }
  return true
}

// 更新密码
const handleUpdatePassword = async () => {
  if (!validatePasswordForm()) return
  
  try {
    const response = await api.post('/api/update_password', {
      new_password: newPassword.value
    })
    
    if (response.data.code === 0) {
      showToast('密码更新成功，即将重新登录', 'success')
      localStorage.removeItem('token')
      setTimeout(() => {
        window.location.href = '/'
      }, 1500)
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('请求失败，请稍后重试', 'error')
  }
}

// 手机号相关
const validatePhoneForm = () => {
  if (!newPhone.value.trim()) {
    showToast('请输入新手机号', 'error')
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(newPhone.value)) {
    showToast('请输入正确的手机号', 'error')
    return false
  }
  if (!verifyCode.value.trim()) {
    showToast('请输入验证码', 'error')
    return false
  }
  if (!/^\d{4}$/.test(verifyCode.value)) {
    showToast('验证码必须是4位数字', 'error')
    return false
  }
  return true
}

// 获取验证码
const handleGetVerifyCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(newPhone.value)) {
    showToast('请输入有效的11位手机号码', 'error')
    return
  }

  // 生成验证码
  try {
    const response = await api.post('/api/verify_code', {
      phone: newPhone.value,
    })
    if (response.data.code === 0) {
      showToast(response.data.message, 'success')
    }
    else{
        showToast(response.data.message, 'error')
      }
  } catch (error) {
    showToast(error.message, 'error')
  }

  // 开始倒计时
  countdown.value = 60
  timer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer.value)
    }
  }, 1000)
}

// 更新手机号
const handleUpdatePhone = async () => {
  if (!validatePhoneForm()) return
  
  try {
    const response = await api.post('/api/update_phone', {
      new_phone: newPhone.value,
      verify_code: verifyCode.value
    })
    
    if (response.data.code === 0) {
      showToast('手机号更新成功', 'success')
      currentPhone.value = newPhone.value
      newPhone.value = ''
      verifyCode.value = ''
      showPhoneForm.value = false
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('请求失败，请稍后重试', 'error')
  }
}

// 通用方法
const resetForms = () => {
  newPassword.value = ''
  confirmPassword.value = ''
  newPhone.value = ''
  verifyCode.value = ''
  clearInterval(timer.value)
  countdown.value = 0
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  window.location.href = '/'
}
</script>

<template>
  <div class="settings-container">
    <Toast />
    <div class="settings-content">
      <h2>用户设置</h2>
      
      <div class="settings-wrapper">
        <!-- 用户名信息 -->
        <div class="info-section">
          <div class="info-item">
            <span class="info-label">用户名：</span>
            <span class="info-value">{{ currentUsername }}</span>
            <button class="edit-btn" @click="() => showUsernameForm = !showUsernameForm">
              {{ showUsernameForm ? '取消' : '修改' }}
            </button>
          </div>
          
          <!-- 修改用户名表单 -->
          <div v-if="showUsernameForm" class="edit-form">
            <div class="form-item">
              <div class="input-label">新用户名：</div>
              <input
                type="text"
                v-model="newUsername"
                placeholder="请输入新用户名（4-16个字符）"
                class="form-input"
              >
            </div>
            <div class="action-btns">
              <button class="confirm-btn" @click="handleUpdateUsername">
                确定
              </button>
            </div>
          </div>
        </div>

        <!-- 密码信息 -->
        <div class="info-section">
          <div class="info-item">
            <span class="info-label">密码：</span>
            <span class="info-value">{{ currentPassword }}</span>
            <button class="edit-btn" @click="() => showPasswordForm = !showPasswordForm">
              {{ showPasswordForm ? '取消' : '修改' }}
            </button>
          </div>
          
          <!-- 修改密码表单 -->
          <div v-if="showPasswordForm" class="edit-form">
            <div class="form-item">
              <div class="input-label">新密码：</div>
              <input
                type="password"
                v-model="newPassword"
                placeholder="请输入新密码（6-16位字母或数字）"
                class="form-input"
              >
            </div>
            <div class="form-item">
              <div class="input-label">确认密码：</div>
              <input
                type="password"
                v-model="confirmPassword"
                placeholder="请再次输入新密码"
                class="form-input"
              >
            </div>
            <div class="action-btns">
              <button class="confirm-btn" @click="handleUpdatePassword">
                确定
              </button>
            </div>
          </div>
        </div>

        <!-- 手机号信息 -->
        <div class="info-section">
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span class="info-value">{{ currentPhone }}</span>
            <button class="edit-btn" @click="() => showPhoneForm = !showPhoneForm">
              {{ showPhoneForm ? '取消' : '修改' }}
            </button>
          </div>
          
          <!-- 修改手机号表单 -->
          <div v-if="showPhoneForm" class="edit-form">
            <div class="form-item">
              <div class="input-label">新手机号：</div>
              <input
                type="text"
                v-model="newPhone"
                placeholder="请输入新手机号"
                class="form-input"
              >
            </div>
            <div class="form-item verify-code">
              <div class="input-label">验证码：</div>
              <input
                type="text"
                v-model="verifyCode"
                placeholder="请输入验证码"
                class="form-input verify-input"
              >
              <button 
                class="code-btn"
                @click="handleGetVerifyCode"
                :disabled="countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </button>
            </div>
            <div class="action-btns">
              <button class="confirm-btn" @click="handleUpdatePhone">
                确定
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 退出登录按钮 -->
      <div class="logout-container">
        <button class="logout-btn" @click="handleLogout">
          退出登录
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.settings-content {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin: 0 20px;
}

.settings-wrapper {
  max-width: 800px;
  margin: 0 auto;
}

h2 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.info-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-label {
  width: 100px;
  color: #606266;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.edit-btn {
  background: #67c23a;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  margin-left: 10px;
}

.edit-btn:hover {
  background: #85ce61;
}

.edit-form {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.form-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.input-label {
  width: 100px;
  text-align: right;
  margin-right: 10px;
  color: #606266;
  font-size: 14px;
}

.form-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  height: 32px;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #409eff;
  outline: none;
}

.verify-code {
  display: flex;
  align-items: center;
}

.verify-input {
  width: 120px;
  flex: none;
}

.code-btn {
  margin-left: 10px;
  min-width: 120px;
  height: 32px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.code-btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.action-btns {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.confirm-btn {
  background: #409eff;
  color: white;
  padding: 8px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.confirm-btn:hover {
  background: #66b1ff;
}

.logout-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.logout-btn {
  background: #f56c6c;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #f78989;
}
</style>
